<template>
    <div ref="parent" class="game-map">
        <canvas ref="canvas" tabindex="0"></canvas>
        
        <!-- 退出按钮 -->
        <div class="exit-button-container">
            <button @click="showExitConfirm = true" class="exit-button">
                <i class="fas fa-sign-out-alt"></i>
            </button>
        </div>
        
        <!-- 退出确认弹窗 -->
        <div v-if="showExitConfirm" class="exit-confirm-overlay">
            <div class="exit-confirm-modal">
                <h3>确定要退出游戏吗？</h3>
                <p>当前游戏进度将不会保存</p>
                <div class="confirm-buttons">
                    <button @click="exitGame" class="confirm-button confirm-yes">
                        确定
                    </button>
                    <button @click="showExitConfirm = false" class="confirm-button confirm-no">
                        取消
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { GameMap } from '@/assets/scripts/mul/GameMap'
import { ref, onMounted, onUnmounted } from 'vue'
import { useGameStore } from '@/store/game'
import { useRouter } from 'vue-router'

export default {
    setup() {
        const gameStore = useGameStore()
        const router = useRouter()
        let parent = ref(null)
        let canvas = ref(null)
        let gameMapInstance = null
        let showExitConfirm = ref(false)

        const handleResize = () => {
            if (!parent.value || !canvas.value) return
            // 获取父容器尺寸并设置canvas尺寸
            canvas.value.width = parent.value.clientWidth
            canvas.value.height = parent.value.clientHeight
            // 如果游戏地图实例存在，则调用resize方法
            if (gameMapInstance) {
                gameMapInstance.resize()
            }
        }
        
        // 退出游戏
        const exitGame = () => {
            showExitConfirm.value = false
            
            // 清理游戏实例
            if (gameMapInstance) {
                try {
                    // 使用GameObject的静态方法清理所有游戏对象
                    const GameObject = gameMapInstance.constructor.constructor
                    if (typeof GameObject.clearAll === 'function') {
                        GameObject.clearAll()
                    }
                    
                    // 清除store中的游戏对象引用
                    gameStore.updateGameObject(null)
                } catch (e) {
                    console.error('清理游戏实例失败')
                }
                
                gameMapInstance = null
            }
            
            // 导航回主菜单
            router.push('/main/')
        }

        // 添加键盘事件监听
        const handleKeyDown = (event) => {
            // Esc键显示退出确认
            if (event.key === 'Escape') {
                if (showExitConfirm.value) {
                    showExitConfirm.value = false
                } else {
                    showExitConfirm.value = true
                }
            }
        }

        onMounted(() => {
            handleResize()

            // 添加键盘事件监听
            if (canvas.value) {
                canvas.value.focus()
                canvas.value.addEventListener('keydown', handleKeyDown)
            }

            // 检查store中是否已有GameMap实例
            if (gameStore.gameObject) {
                // 如果存在旧实例，进行完全清理
                try {
                    // 获取GameObject类引用
                    const GameObject = gameStore.gameObject.constructor.constructor

                    // 先获取所有现有游戏对象的列表快照
                    const allObjects =
                        typeof GameObject.getObjects === 'function'
                            ? GameObject.getObjects().length
                            : 0

                    console.log(`清理前游戏对象数量: ${allObjects}`)

                    // 使用新的clearAll方法进行彻底清理
                    if (typeof GameObject.clearAll === 'function') {
                        GameObject.clearAll()
                    } else {
                        // 备用清理方式
                        if (typeof gameStore.gameObject.destroy === 'function') {
                            gameStore.gameObject.destroy()
                        }
                    }

                    // 验证清理结果
                    if (typeof GameObject.getObjects === 'function') {
                        const remainingObjects = GameObject.getObjects()
                        console.log(`清理后剩余游戏对象数量: ${remainingObjects.length}`)
                    }
                } catch (e) {
                    console.error('清理旧游戏实例失败:', e)
                }
            }

            // 短暂延迟后创建新实例，确保清理完成
            setTimeout(() => {
                try {
                    // 创建新实例
                    gameMapInstance = new GameMap(canvas.value.getContext('2d'))
                    
                    // 确保GameMap实例完全初始化
                    if (gameMapInstance) {
                        // 在更新游戏对象前确保画布尺寸已设置
                        handleResize()
                        
                        // 确保初始化完成后再更新游戏对象
                        setTimeout(() => {
                            if (gameMapInstance && !gameMapInstance._destroyed) {
                                gameStore.updateGameObject(gameMapInstance)
                                
                                // 再次调整大小确保适配
                                handleResize()
                                
                                console.log("GameMap实例创建成功，尺寸:", {
                                    width: gameMapInstance.width,
                                    height: gameMapInstance.height,
                                    playerCount: gameMapInstance.players?.length || 0
                                })
                            }
                        }, 100)
                    }
                } catch (error) {
                    console.error('创建GameMap实例出错:', error)
                }
            }, 100)

            // 添加窗口大小变化的监听器
            window.addEventListener('resize', handleResize)
        })

        onUnmounted(() => {
            window.removeEventListener('resize', handleResize)
            
            // 移除键盘事件监听
            if (canvas.value) {
                canvas.value.removeEventListener('keydown', handleKeyDown)
            }
        })

        return {
            parent,
            canvas,
            showExitConfirm,
            exitGame
        }
    },
}
</script>

<style scoped>
.game-map {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    position: relative;
}

canvas {
    display: block;
}

/* 退出按钮样式 */
.exit-button-container {
    position: absolute;
    top: 1rem;
    right: 1rem;
    z-index: 10;
}

.exit-button {
    background: rgba(0, 0, 0, 0.5);
    color: #00ff88;
    border: 1px solid rgba(0, 255, 136, 0.3);
    padding: 0.5rem;
    width: 38px;
    height: 38px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.exit-button:hover {
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(0, 255, 136, 0.5);
    background: rgba(0, 255, 136, 0.2);
}

.exit-button i {
    font-size: 1rem;
}

/* 退出确认弹窗样式 */
.exit-confirm-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 110;
    backdrop-filter: blur(5px);
}

.exit-confirm-modal {
    background: #1a1a1a;
    border-radius: 12px;
    width: 90%;
    max-width: 400px;
    padding: 2rem;
    text-align: center;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
    border: 2px solid rgba(255, 77, 77, 0.3);
    animation: fadeIn 0.3s ease;
}

.exit-confirm-modal h3 {
    font-size: 1.8rem;
    margin-bottom: 1rem;
    color: #ff4d4d;
    text-shadow: 0 0 10px rgba(255, 77, 77, 0.5);
}

.exit-confirm-modal p {
    margin-bottom: 2rem;
    font-size: 1.2rem;
    color: #ddd;
}

.confirm-buttons {
    display: flex;
    gap: 1rem;
    justify-content: center;
}

.confirm-button {
    padding: 0.8rem 2rem;
    border-radius: 6px;
    font-size: 1.1rem;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
    width: 120px;
}

.confirm-button:hover {
    transform: scale(1.05);
}

.confirm-button.confirm-yes {
    background: rgba(255, 77, 77, 0.1);
    color: #ff4d4d;
    border: 1px solid rgba(255, 77, 77, 0.3);
}

.confirm-button.confirm-yes:hover {
    background: rgba(255, 77, 77, 0.2);
    box-shadow: 0 0 15px rgba(255, 77, 77, 0.5);
}

.confirm-button.confirm-no {
    background: rgba(0, 255, 136, 0.1);
    color: #00ff88;
    border: 1px solid rgba(0, 255, 136, 0.3);
}

.confirm-button.confirm-no:hover {
    background: rgba(0, 255, 136, 0.2);
    box-shadow: 0 0 15px rgba(0, 255, 136, 0.5);
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
